package com.draven.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.draven.mall.entity.MerchantApplication;
import com.draven.mall.entity.RiderApplication;
import com.draven.mall.mapper.MerchantApplicationMapper;
import com.draven.mall.mapper.RiderApplicationMapper;
import com.draven.mall.service.ApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 入驻申请服务实现类
 */
@Service
public class ApplicationServiceImpl implements ApplicationService {

    @Autowired
    private MerchantApplicationMapper merchantApplicationMapper;

    @Autowired
    private RiderApplicationMapper riderApplicationMapper;

    @Value("${file.upload.path:/uploads}")
    private String uploadPath;

    @Value("${file.access.url:http://localhost:8080/uploads}")
    private String accessUrl;

    /**
     * 提交商家入驻申请
     */
    @Override
    @Transactional
    public boolean submitMerchantApplication(MerchantApplication application) {
        // 设置初始状态为待审核
        application.setStatus(0);
        application.setCreateTime(new Date());
        
        // 检查是否已经存在申请
        LambdaQueryWrapper<MerchantApplication> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MerchantApplication::getPhone, application.getPhone());
        long count = merchantApplicationMapper.selectCount(wrapper);
        if (count > 0) {
            return false;
        }
        
        return merchantApplicationMapper.insert(application) > 0;
    }

    /**
     * 提交骑手入驻申请
     */
    @Override
    @Transactional
    public boolean submitRiderApplication(RiderApplication application) {
        // 设置初始状态为待审核
        application.setStatus(0);
        application.setCreatedTime(new Date());
        
        // 检查是否已经存在申请
        LambdaQueryWrapper<RiderApplication> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RiderApplication::getPhone, application.getPhone());
        long count = riderApplicationMapper.selectCount(wrapper);
        if (count > 0) {
            return false;
        }
        
        return riderApplicationMapper.insert(application) > 0;
    }

    /**
     * 查询商家申请状态
     */
    @Override
    public Map<String, Object> getMerchantApplicationStatus(String phone) {
        Map<String, Object> result = new HashMap<>();
        
        // 查询申请信息
        LambdaQueryWrapper<MerchantApplication> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MerchantApplication::getPhone, phone)
               .orderByDesc(MerchantApplication::getCreateTime)
               .last("LIMIT 1");
        
        MerchantApplication application = merchantApplicationMapper.selectOne(wrapper);
        
        if (application != null) {
            result.put("exists", true);
            result.put("status", application.getStatus());
            result.put("statusText", getStatusText(application.getStatus()));
            result.put("rejectReason", application.getRejectReason());
            result.put("submitTime", application.getCreateTime());
            if (application.getAuditTime() != null) {
                result.put("auditTime", application.getAuditTime());
            }
        } else {
            result.put("exists", false);
        }
        
        return result;
    }

    /**
     * 查询骑手申请状态
     */
    @Override
    public Map<String, Object> getRiderApplicationStatus(String phone) {
        Map<String, Object> result = new HashMap<>();
        
        // 查询申请信息
        LambdaQueryWrapper<RiderApplication> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RiderApplication::getPhone, phone)
               .orderByDesc(RiderApplication::getCreatedTime)
               .last("LIMIT 1");
        
        RiderApplication application = riderApplicationMapper.selectOne(wrapper);
        
        if (application != null) {
            result.put("exists", true);
            result.put("status", application.getStatus());
            result.put("statusText", getStatusText(application.getStatus()));
            result.put("rejectReason", application.getRejectReason());
            result.put("submitTime", application.getCreatedTime());
            if (application.getAuditTime() != null) {
                result.put("auditTime", application.getAuditTime());
            }
        } else {
            result.put("exists", false);
        }
        
        return result;
    }

    /**
     * 上传文件
     */
    @Override
    public String uploadFile(MultipartFile file) {
        if (file.isEmpty()) {
            return null;
        }
        
        // 创建文件保存目录
        String datePath = new SimpleDateFormat("yyyyMMdd").format(new Date());
        File uploadDir = new File(uploadPath + "/" + datePath);
        if (!uploadDir.exists()) {
            if (!uploadDir.mkdirs()) {
                return null;
            }
        }
        
        // 生成新的文件名
        String originalFileName = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFileName != null && originalFileName.contains(".")) {
            fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        }
        String newFileName = UUID.randomUUID().toString() + fileExtension;
        
        // 保存文件
        File destFile = new File(uploadDir.getAbsolutePath() + File.separator + newFileName);
        try {
            file.transferTo(destFile);
            // 返回文件访问URL，使用API接口格式
            return "/api/files/" + datePath + "/" + newFileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 获取状态文本描述
     */
    private String getStatusText(Integer status) {
        if (status == null) {
            return "未知";
        }
        
        switch (status) {
            case 0:
                return "待审核";
            case 1:
                return "审核通过";
            case 2:
                return "审核拒绝";
            default:
                return "未知";
        }
    }
} 